import router from '@/router/index'
import { asyncRoutes } from '@/router/asyncRoutes'
export function hasPermission(route, menus) {
  if (!route.name) return true

  const check = (menus) => {
    for (const menu of menus) {
      if (menu.name === route.name) return true
      if (menu.children && check(menu.children)) return true
    }
    return false
  }
  return check(menus)
}

export function filterAsyncRoutes(routes, menus) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(tmp, menus)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, menus)
      }
      res.push(tmp)
    }
  })
  console.log("res:",res)
  return res
}

// 设置动态路由
export function setupDynamicRoutes(userMenus) {
  return new Promise((resolve) => {
    const accessRoutes = filterAsyncRoutes(asyncRoutes, userMenus)

    // 判断是否包含首页菜单，如果有则跳转到首页
    const hasIndexMenu = userMenus.some(menu => menu.title === '首页')
    
    // 动态添加路由
    accessRoutes.forEach(route => {
      router.addRoute(route)
    })

    // 确保路由挂载完成后再跳转
    resolve()

    // 如果有首页菜单，跳转到首页
    if (hasIndexMenu) {
      router.push('/app/index')
    } else {
      router.push('/app') // 或者设置一个默认路由
    }
  })
}
